package cn.plushine.controller;

import cn.plushine.utils.ResMapUtils;
import cn.plushine.utils.UploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;


@Api(tags = "文件上传模块")
@RestController
@RequestMapping("/admin/product/")
public class FileUploadController {

    /**
     * 文件上传
     * 教程：https://blog.csdn.net/weixin_39614177/article/details/113542058
     * 403问题：https://blog.csdn.net/weixin_38689747/article/details/89641333
     */
    @ApiOperation(value = "文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "待上传的文件", required = true, paramType = "form", dataType = "__file")
    })
    @PostMapping("/fileUpload")
    public HashMap<String, Object> fileUpload(@RequestParam("file") MultipartFile multipartFile) {
        // 文件为空
        if (multipartFile.isEmpty()) {
            return ResMapUtils.encapsulation(201, "文件不能为空！", null);
        }
        // 文件非空
        try {
            // 调用七牛云文件上传工具类，上传文件
            String url = UploadUtils.uploadFile(multipartFile);
            // 文件上传成功
            return ResMapUtils.encapsulation(200, "文件上传成功！", url);
        } catch (Exception e) {
            // 文件上传失败
            return ResMapUtils.encapsulation(202, "文件上传失败！", e.getMessage());
        }
    }
}
